<template>
    <div>
        <van-dialog v-model="showCode" :title="phone" 
            :before-close='beforeClose'
            @confirm='confirm'
            @cancel='cancel'
            show-cancel-button>
           <!-- <div class="phone">手机：{{phone}}</div> -->
            <van-field
                    v-model.trim="sms"
                    center
                    clearable
                    label="验证码"
                    placeholder="输入短信验证码"
                    >
                    <template #button>
                        <van-button @click="sendCode" size="small" type="primary">
                           <span v-if="count >= time">发送验证码</span>
                           <span v-else>{{count}}秒</span>
                        </van-button>
                       
                    </template>
                </van-field>
        </van-dialog>
    </div>
</template>
<script>
import {sendVerficationCode} from '@/api/loginApi'
export default {
    props: {
        phone: String
    },
    data () {
        return {
            text: '发送验证码',
            showCode: false,
            sms: '',
            count: 60,
            time: 60
        }
    },
    methods: {
        show() {
            this.showCode = true
        },
        beforeClose (action, done) {
             done(false)
        },
        confirm () {
            if (this.sms) {
                this.showCode = false
                this.$emit('comfirm', this.sms)
            } else {
                this.$toast.fail('请输入短信验证码')
            }
            
        },
        cancel () {
            this.showCode = false
        },
        async sendCode () {
            if (this.count < this.time) {
                return 
            }
            let res = await sendVerficationCode({phone: this.phone})
            console.log(res)
            this.$toast.success(res.msg)
            this.countDown()
        },
        countDown () {
            this.count--
            if (this.count <= 0) {
                this.count = this.time
                return
            }
            setTimeout(() => {
                this.countDown()
            }, 1000)
        }
    }
}
</script>
<style scoped>
.phone{
    padding: 0.1rem 0.16rem;
}
</style>
